<template>
  <div class="register-page">
    <div class="factory-bg"></div>
    <el-card shadow="never" class="card">
      <template #header>
        <div class="header">
          <span>注册新用户</span>
        </div>
      </template>
      <el-row :gutter="16">
        <el-col :span="8">
          <div class="avatar-panel">
            <el-upload class="avatar-uploader" :show-file-list="false" :http-request="handleCustomUpload"
              :before-upload="beforeAvatarUpload">
              <img v-if="form.iocn" :src="imagePreviewUrl" class="avatar" />
              <div v-else class="avatar-placeholder">
                <el-icon>
                  <Plus />
                </el-icon>
                <div>上传头像</div>
              </div>
            </el-upload>
            <div class="tips">支持 jpg/png，≤ 2MB</div>
          </div>
        </el-col>
        <el-col :span="16">
          <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" status-icon>
            <el-form-item label="账号" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入账号" clearable />
            </el-form-item>
            <el-form-item label="昵称" prop="userNickname">
              <el-input v-model="form.userNickname" placeholder="请输入昵称" clearable />
            </el-form-item>
            <el-form-item label="密码" prop="userPass">
              <el-input v-model="form.userPass" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
            <el-form-item label="角色" prop="roleId">
              <el-select v-model="form.roleId" placeholder="请选择角色" filterable :loading="rolesLoading"
                style="width: 100%">
                <el-option v-for="r in roleOptions" :key="r.value" :label="r.label" :value="r.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="工厂" prop="factoryId">
              <el-select v-model="form.factoryId" placeholder="请选择工厂" filterable :loading="factoriesLoading"
                style="width: 100%">
                <el-option v-for="f in factoryOptions" :key="f.value" :label="f.label" :value="f.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio :label="true">男</el-radio>
                <el-radio :label="false">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="组织框架" prop="deptId">
              <el-select v-model="form.deptId" placeholder="请选择组织框架" :no-data-text="'暂无组织数据'" filterable
                :loading="orgLoading" style="width: 100%" @change="onDeptChange">
                <el-option v-for="d in orgOptions" :key="d.value" :label="d.label" :value="d.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :loading="submitting" @click="onSubmit">注册</el-button>
              <el-button @click="goLogin">返回登录</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { APIs, getImageUrl } from '@/Http/http'
import { Plus } from '@element-plus/icons-vue'
import { useCounterStore } from '@/stores/counter'

const router = useRouter()
const store = useCounterStore()
const formRef = ref<FormInstance>()
const submitting = ref(false)
const rolesLoading = ref(false)
const roleOptions = ref<Array<{ label: string, value: number }>>([])
const factoriesLoading = ref(false)
const factoryOptions = ref<Array<{ label: string, value: number }>>([])
const orgLoading = ref(false)
const orgOptions = ref<Array<{ label: string, value: number }>>([])

type RegisterForm = {
  userId?: number
  userName: string
  userPass: string
  userNickname: string
  iocn: string
  roleId: number | null
  factoryId: number | null
  sex: boolean
  deptId: number | null
}

const form = reactive<RegisterForm>({
  userName: '',
  userPass: '',
  userNickname: '',
  iocn: '',
  roleId: null,
  factoryId: null,
  sex: true,
  deptId: null
})

const rules = reactive<FormRules<RegisterForm>>({
  userName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  userPass: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
  factoryId: [{ required: true, message: '请选择工厂', trigger: 'change' }],
})

const imagePreviewUrl = computed(() => {
  if (!form.iocn) return ''
  return getImageUrl(form.iocn)
})

async function loadRoles() {
  try {
    rolesLoading.value = true
    const res = await APIs.get('/api/Read/GetRoleListForDropdown')
    const list = Array.isArray(res?.data) ? res.data : (res?.data?.data || [])
    roleOptions.value = list.map((it: any) => ({
      value: Number(it.roleId ?? it.id ?? it.RoleId ?? 0),
      label: String(it.roleName ?? it.name ?? '')
    })).filter((x: any) => x.value)
  } catch (e) {
    ElMessage.error('角色加载失败')
  } finally {
    rolesLoading.value = false
  }
}

async function loadFactories() {
  try {
    factoriesLoading.value = true
    const res = await APIs.get('/api/Read/FactorySelect')
    const list = Array.isArray(res?.data) ? res.data : (res?.data?.data || [])
    factoryOptions.value = list.map((it: any) => ({
      value: Number(it.factoryId ?? it.id ?? it.FactoryId ?? 0),
      label: String(it.factoryName ?? it.name ?? it.FactoryName ?? '')
    })).filter((x: any) => x.value)
  } catch (e) {
    ElMessage.error('工厂加载失败')
  } finally {
    factoriesLoading.value = false
  }
}

async function loadOrgOptions() {
  try {
    orgLoading.value = true
    // 复用已有页面的接口约定，优先尝试 OrcanSelect，不存在则降级到 OrcanQuery
    let list: any[] = []
    try {
      const res1 = await APIs.get('/api/Read/OrcanSelect')
      list = Array.isArray(res1?.data) ? res1.data : (res1?.data?.data || [])
    } catch (_) {
      const res2 = await APIs.get('/api/Read/OrcanQuery', { params: { pageIndex: 1, pageSize: 9999 } })
      list = Array.isArray(res2?.data?.data?.data) ? res2.data.data.data : []
    }
    orgOptions.value = list.map((it: any) => ({
      // 优先使用 oranId，其次才是 deptId，避免所有项都映射为相同的 deptId=555
      value: Number(it.oranId ?? it.deptId ?? it.id ?? it.DeptId ?? 0),
      label: String(it.oranCordName ?? it.deptName ?? it.name ?? it.DeptName ?? '')
    })).filter(x => x.value)
    if (!orgOptions.value.length) {
      ElMessage.warning('暂无组织数据，请先在组织管理中新增')
    }
    // 预设为 null 以显示占位
    form.deptId = null
  } catch (e) {
    ElMessage.error('组织框架加载失败')
  } finally {
    orgLoading.value = false
  }
}

function onDeptChange(val: number) {
  // 防止出现错误值，强制转 number
  form.deptId = Number(val) || null
}

function beforeAvatarUpload(file: File) {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isImage) ElMessage.error('仅支持 JPG/PNG 格式')
  if (!isLt2M) ElMessage.error('图片大小不能超过 2MB')
  return isImage && isLt2M
}

async function handleCustomUpload(options: any) {
  const { file, onSuccess, onError } = options
  try {
    const fd = new FormData()
    fd.append('file', file)
    // 对应你的上传接口
    const res = await APIs.post('/api/Write/FileWiter', fd, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    // 假设返回 { code: 200, data: 'uploads/avatar.png' }
    const filename = res?.data?.data || res?.data?.fileName || res?.data
    if (!filename) throw new Error('上传返回无文件名')
    form.iocn = filename
    ElMessage.success('头像上传成功')
    onSuccess(res)
  } catch (err: any) {
    ElMessage.error(err?.message || '头像上传失败')
    onError?.(err)
  }
}

async function onSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    if (!form.deptId) {
      ElMessage.error('请选择组织框架')
      return
    }
    try {
      submitting.value = true
      const payload = {
        data: {
          createName: store.Users.userNickname || form.userName,
          createTime: new Date().toISOString(),
          updateName: '',
          updateTime: new Date().toISOString(),
          deleteName: '',
          deleteTime: new Date().toISOString(),
          isDel: false,
          userId: 0,
          userName: form.userName,
          userPass: form.userPass,
          userNickname: form.userNickname,
          iocn: form.iocn || '',
          factoryId: Number(form.factoryId) || 0,
          sex: Boolean(form.sex),
          deptId: Number(form.deptId) || 0
        },
        roleData: {
          id: 0,
          userId: 0,
          roleId: Number(form.roleId) || 0
        }
      }
      const res = await APIs.post('/api/Write/AccountCreate', payload)
      if (res && (res.status === 200 || res.status === 201)) {
        ElMessage.success('注册成功')
        router.push('/')
      } else {
        ElMessage.error('注册失败')
      }
    } catch (e: any) {
      ElMessage.error(e?.response?.data?.message || '请求失败')
    } finally {
      submitting.value = false
    }
  })
}

function goLogin() {
  router.push('/')
}

onMounted(() => {
  loadRoles()
  loadFactories()
  loadOrgOptions()
})
</script>

<style scoped>
.register-page {
  min-height: 100vh;
  padding: 24px;
  background: url('/icons/selection.png') no-repeat center center fixed;
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: center;
}

.card {
  max-width: 1100px;
  margin: 0 auto;
  background-color: rgba(255, 255, 255, 0.92);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.factory-bg {
  position: absolute;
  inset: 0;
  background: url('/icons/selection.png') no-repeat right bottom;
  background-size: 40%;
  opacity: 0.15;
  pointer-events: none;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.avatar-panel {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.avatar-uploader {
  width: 220px;
  height: 220px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-placeholder {
  color: var(--el-text-color-secondary);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
}

.avatar {
  width: 220px;
  height: 220px;
  object-fit: cover;
  border-radius: 6px;
}

.tips {
  color: var(--el-text-color-secondary);
  font-size: 12px;
}
</style>
